package cn.datawin.co.corule.service.client;

import java.util.HashMap;
import java.util.Map;

import com.googlecode.jsonplugin.JSONException;
import com.googlecode.jsonplugin.JSONUtil;
import com.mongodb.DBObject;
import cn.datawin.Client;
import cn.datawin.Rule;
import cn.datawin.crule.ServiceBuilder;
import cn.datawin.co.corule.bo.CoTask;
import cn.datawin.co.corule.bo.CoTaskResult;
import cn.datawin.util.HttpUtil;

public class CoService extends cn.datawin.crule.CoService {
	
	
	private Rule rule;
	
	CoClient client;

	@Override
	public Client getClient() {
		return client;
	}
	
	public CoService() {
		// TODO Auto-generated constructor stub
	}

	public CoService(Client client, Class<? extends Rule> _class) {
		this.client = (CoClient) client;
		rule = ServiceBuilder.getInstance().build(_class);
		rule.setClient(client);
		rule.setService(this);
	}

	/**
	 * 通过 返回 的taskid 来保持service
	 */
	public void doo() {
		rule.do_("first");
	}

	public void dooResult(DBObject r) {
		CoTaskResult ctr = dboToCTR(r);
		rule.setObject(ctr);
		rule.do_(ctr.getSig() + "Result");
	}
	
	@Override
	public void exec() {
		if(isDone()) return;
		CoTask task = rule.getObject(CoTask.class);
		String cid = (client).getClientid();
		task.setClientid(cid);
		insert(task);
		(client).setService(task.getId(), this);
	}
	
	public void insert(CoTask task){
		try {
			String coTask = JSONUtil.serialize(task);
			System.out.println(coTask);
			Map<String,String> map = new HashMap<String, String>();
			map.put("coTask",coTask);
			HttpUtil.post("http://127.0.0.1/spider/cotask/insertcotask", map);
			
		} catch (JSONException e) {
			System.out.println("CoService-insert()--cotaskService.insertCoTask(JSONUtil.serialize(task));");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public CoTaskResult dboToCTR(DBObject r){
		CoTaskResult ctr = new CoTaskResult();
		ctr.setClientid(r.get("clientid").toString());
		ctr.setId(r.get("_id").toString());
		ctr.setResult((Map<String, Object>)r.get("result"));
		ctr.setSig(r.get("sig").toString());
		ctr.setState(r.get("state").toString());
		ctr.setTaskid(r.get("taskid").toString());
		ctr.setType(r.get("type").toString());
		ctr.setWorkbeach(r.get("workbeach").toString());
		return ctr;
	}

}
